import {
  Application,
  DbAsyncDoc,
  DbAsyncReturn,
  DbAsyncStorage,
  DbStorage
} from "@/module/storage/types";
import { del, get, set } from "idb-keyval";
import MessageUtil from "@/utils/model/MessageUtil";

export const dbStorageForCommon: DbStorage = {
  setItem: (key: string, value: any) => {
    localStorage.setItem(key, JSON.stringify({ value }));
  },
  getItem: (key: string) => {
    const value = localStorage.getItem(key);
    if (value) {
      return JSON.parse(value).value;
    }
    return null;
  },
  removeItem: (key: string) => {
    localStorage.removeItem(key);
  }
};
export const dbAsyncStorageForCommon: DbAsyncStorage = {
  /**
   * 创建/更新文档
   */
  async put(doc: DbAsyncDoc): Promise<DbAsyncReturn> {
    try {
      await set(doc._id, doc);
      return Promise.resolve({
        id: doc._id,
        rev: ""
      });
    } catch (e) {
      return Promise.resolve({
        id: doc._id,
        error: true,
        message: `${e}`,
        ok: false
      });
    }
  },
  /**
   * 获取文档
   */
  get: (id: string) => {
    return get(id);
  },
  /**
   * 删除文档
   */
  async remove(id: string): Promise<DbAsyncReturn> {
    try {
      await del(id);
      return Promise.resolve({
        id,
        rev: ""
      });
    } catch (e) {
      return Promise.resolve({
        id,
        error: true,
        message: `${e}`,
        ok: false
      });
    }
  }
};

export const applicationForCommon: Application = {
  copyText: (text) => {
    navigator.clipboard.writeText(text).catch((e) => MessageUtil.error("复制失败", e));
  },
  shellOpenExternal: (url) => {
    window.open(url);
  }
};
